//
//  NSObject+PYDownloadSingleImage.m
//  catuncel
//
//  Created by Jim on 2018/1/17.
//  Copyright © 2018年 Jim. All rights reserved.
//

#import "NSObject+PYDownloadSingleImage.h"

@implementation NSObject (PYDownloadSingleImage)

+ (void)downloadSingleImageWithURL:(NSURL *)url completion:(void (^)(UIImage *image))completion
{
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    
    [request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
    
    NSURLSession* session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        py_dispatch_async_main_safe(^{
            
            if (data) {
                
                UIImage *image = [UIImage imageWithData:data];
                
                if (completion) {
                    
                    completion(image);
                    
                }
                
            } else {
                
                NSLog(@"下载单张图片失败");                
            }
        });
    }];
    
    //开启网络请求任务
    [task resume];
}

@end
